﻿using AopFilters.Models;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AopFilters
{
    /// <summary>
    /// 方法AOP （最适合做日志）（在接口执行前后做动作）
    /// </summary>
    public class KmAsyncActionFilter : IAsyncActionFilter
    {
        private readonly ILogger<KmAsyncActionFilter> _logger;
        public KmAsyncActionFilter(ILogger<KmAsyncActionFilter> logger)
        {
            _logger = logger;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            throw new ApiException("身份认证失效", ErrorCode.Auth);
            if (context.IfIgnoreFilter(typeof(KmAsyncActionFilter))) 
            {
                await next.Invoke();
                return;
            }        
            //接口执行前动作...
            Console.WriteLine("【ActionFilter】开始...");
            //object? controllerName = context.HttpContext.GetRouteValue("controller");
            //object? actionName = context.HttpContext.GetRouteValue("action");
            //_logger.LogInformation($"控制器：{controllerName}，方法：{actionName}");

            ActionExecutedContext actionResult = await next.Invoke();//执行接口方法

            //接口执行后动作...
            //string result = JsonConvert.SerializeObject(actionResult.Result);
            //_logger.LogInformation($"执行结果：{result}");
            Console.WriteLine("【ActionFilter】结束。");
        }
    }
}
